package com.wenjh.jdmzt.android.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.FrameLayout;

import com.umeng.analytics.MobclickAgent;
import com.umeng.update.UmengUpdateAgent;
import com.wenjh.jdmzt.R;
import com.wenjh.jdmzt.android.synctask.BaseTask;
import com.wenjh.jdmzt.android.view.ActionButton;
import com.wenjh.jdmzt.android.view.MAlertDialog;
import com.wenjh.jdmzt.protocol.HttpClient;
import com.wenjh.jdmzt.service.ImageService;
import com.wenjh.jdmzt.service.model.Image;
import com.wenjh.jdmzt.util.Toaster;
import com.zhuamob.android.ZhuamobLayout;

public class MainActivity extends ScrollTabGroupActivity implements OnClickListener {
	public final static String KEY_SHOWINDEX = "showindex";
	private LoadMoreTask loadMoreTask = null;
	private ReflushTask reflushTask = null;
	private List<Image> imageList = new ArrayList<Image>();
	private int page = 0;
	private int setPage = 0;
	private ImageService imageService = null;
	boolean reflushSuccess = false;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		MobclickAgent.onError(this);
		UmengUpdateAgent.setUpdateOnlyWifi(false);
		UmengUpdateAgent.update(this);
		initViews();
		addTab(ListPicFragment.class, GridPicFragment.class);
		findViewById(R.id.tab_layout_list).setOnClickListener(this);
		findViewById(R.id.tab_layout_grid).setOnClickListener(this);
		imageService = new ImageService();
		executeAsyncTask(new LoadCacheImage(this));
		page = getApp().publicPreference.get("page", 0);
		
		ZhuamobLayout zhuamobLayout = new ZhuamobLayout(this);
		FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
				FrameLayout.LayoutParams.FILL_PARENT,
				FrameLayout.LayoutParams.WRAP_CONTENT);
		params.gravity = Gravity.BOTTOM;
//		zhuamobLayout.setBackgroundColor(getResources().getColor(R.color.banner_bg));
		addContentView(zhuamobLayout, params);
	}

	public List<Image> getImageList() {
		return imageList;
	}
	
	@Override
	protected void initViews() {
		addHeaderButton(new ActionButton(getApplicationContext()).setText("翻页"), new OnClickListener() {
			@Override
			public void onClick(View v) {
				final EditText editText = new EditText(getApplicationContext());
				editText.setInputType(EditorInfo.TYPE_CLASS_NUMBER);
				editText.setText(page+"");
				editText.setTextColor(Color.BLACK);
				MAlertDialog dialog = MAlertDialog.makeConfirm(MainActivity.this, "", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						try {
							int page = Integer.parseInt(editText.getText().toString());
							MainActivity.this.setPage = page;
							((MainTabOptionFragment)getFragment(getCurrentTab())).pullToReflush();
						} catch (Exception e) {
							if(MainActivity.this.setPage != 0) {
								MainActivity.this.setPage = 0;
								((MainTabOptionFragment)getFragment(getCurrentTab())).pullToReflush();
							}
						}
					}
				});
				dialog.setContentView(editText);
				dialog.show();
			}
		});
		
		addHeaderButton(new ActionButton(getApplicationContext()).setIconResource(R.drawable.ic_setting_normal), new OnClickListener() {
			@Override
			public void onClick(View v) {
				startActivity(new Intent(getApplicationContext(), SettingActivity.class));
			}
		});
	}
	
	@Override
	protected void onTabChanged(Fragment fragment, int position) {
		switch (position) {
		case 0:
			findViewById(R.id.tab_layout_list).setSelected(true);
			findViewById(R.id.tab_layout_grid).setSelected(false);
			break;
		case 1:
			findViewById(R.id.tab_layout_grid).setSelected(true);
			findViewById(R.id.tab_layout_list).setSelected(false);
			break;

		default:
			break;
		}
		
		((TabOptionFragment) fragment).fillingHeader(this, getHeaderBar());
	}
	
	public void reflush() {
		executeAsyncTask(new ReflushTask(this));
	}
	
	public void loadMore() {
		executeAsyncTask(new LoadMoreTask(this));
	}
	
	public boolean isMoreLoding() {
		return loadMoreTask != null && !loadMoreTask.isCancelled();
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		ZhuamobLayout.clean();
	}

	public void onImageClick(int index) {
		String[] imagearray = new String[imageList.size()];
		for (int i = 0; i < imageList.size(); i++) {
			imagearray[i] = imageList.get(i).getUrlString();
		}
		
		Image image = imageList.get(index);
		
		Intent intent = new Intent(getApplicationContext(), ImageBrowserActivity.class);
		intent.putExtra(ImageBrowserActivity.KEY_IMAGES_URLARRAY, imagearray);
		intent.putExtra(ImageBrowserActivity.KEY_INDEX, index);
		startActivity(intent);
		
		Map<String, String> params = new HashMap<String, String>();
	    params.put("type", image.getType()+"");
	    params.put("imgid", image.getId());
	    params.put("imgsupport", image.getSupportCount()+"");
	    params.put("imgunsupport", image.getUnsupportCount()+"");
	    params.put("imgurl", image.getUrlString());
	    if(getCurrentTab() == 0) {
	    	params.put("from", "list");
	    } else {
	    	params.put("from", "grid");
	    }
	    MobclickAgent.onEvent(this, "imageitemclick", params);
	}
	
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.tab_layout_list:
			if(getCurrentTab() == 0) {
				((MainTabOptionFragment)getFragment(0)).scrollToTop();
			} else {
				setCurrentTab(0);
			}
			break;
		case R.id.tab_layout_grid:
			if(getCurrentTab() == 1) {
				((MainTabOptionFragment)getFragment(1)).scrollToTop();
			} else {
				setCurrentTab(1);
			}
			break;
		default:
			break;
		}
	}
	
	private class ReflushTask extends BaseTask<Object, Object, List<Image>> {
		public ReflushTask(Context context) {
			super(context);
			if(reflushTask != null) {
				reflushTask.cancel();
			}
			reflushTask = this;
		}

		@Override
		protected void onPreTask() {
			if(loadMoreTask != null) {
				loadMoreTask.cancel();
				loadMoreTask = null;
			}
		}
		
		@Override
		protected List<Image> executeTask(Object... params) throws Exception {
			List<Image> list = new ArrayList<Image>();
			page = HttpClient.downloadImageList(setPage, list);
			imageService.saveImage(list);
			getApp().publicPreference.put("page", page);
			return list;
		}
		
		@Override
		protected void onTaskSuccess(List<Image> result) {
			reflushSuccess = true;
			imageList.clear();
			imageList.addAll(result);
		}
		
		@Override
		protected void onTaskFinish() {
			((MainTabOptionFragment)getFragment(0)).onReflushComplete();
			((MainTabOptionFragment)getFragment(1)).onReflushComplete();
			reflushTask = null;
		}
		
		public void cancel() {
			cancel(true);
			onTaskFinish();
		}
	}

	private class LoadMoreTask extends BaseTask<Object, Object, List<Image>> {
		public LoadMoreTask(Context context) {
			super(context);
			if(loadMoreTask != null) {
				loadMoreTask.cancel();
			}
			loadMoreTask = this;
		}
		
		@Override
		protected List<Image> executeTask(Object... params) throws Exception {
			if(page > 1) {
				List<Image> list = new ArrayList<Image>();
				page = HttpClient.downloadImageList(--page, list);
				imageService.addImages(list);
				return list;
			} else {
				return null;
			}
		}
		
		@Override
		protected void onTaskSuccess(List<Image> result) {
			if(result != null) {
				imageList.addAll(result);
			}
		}
		
		@Override
		protected void onTaskFinish() {
			loadMoreTask = null;
			((MainTabOptionFragment)getFragment(0)).onLoadMoreComplete();
			((MainTabOptionFragment)getFragment(1)).onLoadMoreComplete();
		}
		
		public void cancel() {
			cancel(true);
			onTaskFinish();
		}
	}
	
	
	private class LoadCacheImage extends BaseTask<Object, Object, List<Image>> {
		public LoadCacheImage(Context context) {
			super(context);
		}
		
		@Override
		protected List<Image> executeTask(Object... params) throws Exception {
			return imageService.findImages();
		}
		
		@Override
		protected void onTaskSuccess(List<Image> result) {
			if(result.size() > 0 && !reflushSuccess) {
				imageList.addAll(result);
				if(isAllInited()) {
					((MainTabOptionFragment)getFragment(0)).refulshData();
					((MainTabOptionFragment)getFragment(1)).refulshData();
				}
			} else if(result.isEmpty() && !getApp().publicPreference.get("alertuser", false)) {
				getApp().publicPreference.put("alertuser", true);
				Toaster.show("首次启动可能需要更多时间加载图片，请耐心等待", Toaster.LENGTH_LONG);
			}
		}
	}
}
